#include "strcliselect.h"
#include <define.h>
#include <error.h>
#include <sockfunc.h>
#include <wrapfunc.h>
#include <stdio.h>
#include <string.h>


void 
str_cli01(FILE *fp, int fd) {
	char readbuf[MAX_LINE], writebuf[MAX_LINE];
	fd_set rset;
	int maxfd1;
	int fno = fileno(fp);

	FD_ZERO(&rset);
	for (;;) {
		FD_SET(fd, &rset);
		FD_SET(fno, &rset);
		maxfd1 = (fno > fd ? fno : fd) + 1;
		Select(maxfd1, &rset, NULL, NULL, NULL);

		if (FD_ISSET(fd, &rset)) {
			if (Readline_buffer(fd, readbuf, sizeof(readbuf)) == 0) {
				error_msg("the connection is closed");
				break;
			}
			error_msg(":%s", readbuf);
		}
		if (FD_ISSET(fno, &rset)) {
			if (fgets(writebuf, sizeof(writebuf), fp) == NULL)
				break;
			Writen(fd, writebuf, strlen(writebuf));
		}
	}
}

// 直接 read 不使用带缓冲区的函数，比如 fgets 因为 select 无法知道这些函数的缓冲区中是否有数据。
void
str_cli02(FILE *fp, int fd) {
	char readbuf[MAX_LINE], writebuf[MAX_LINE];
	int stdeof = 0;
	fd_set rset;
	int maxfd1;
	int fno = fileno(fp);
	ssize_t n;

	FD_ZERO(&rset);
	for (;;) {
		if (!stdeof)
			FD_SET(fno, &rset);
		FD_SET(fd, &rset);
		maxfd1 = (fno > fd ? fno : fd) + 1;
		Select(maxfd1, &rset, NULL, NULL, NULL);

		if (FD_ISSET(fd, &rset)) {
			if ((n=Read(fd, readbuf, sizeof(readbuf)-1)) == 0) {
				error_msg("the connection is closed");
				break;
			}
			
			readbuf[n] = 0;
			error_msg(":%s", readbuf);
			// Write(fileno(stdout), readbuf, n);
		}

		if (FD_ISSET(fno, &rset)) {
			if ((n=read(fno, writebuf, sizeof(writebuf))) == 0) {
				stdeof = 1;
				Shutdown(fd, SHUT_WR);
				FD_CLR(fno, &rset);
				continue;
			}
			writebuf[n-1] = 0; // set \n to 0
			Writen(fd, writebuf, strlen(writebuf));
		}
	}
}
